package toOffer;

/**
 * @author YuanAo
 * @date 2024/12/13 9:44
 * @description 狒狒吃香蕉
 */

import java.util.ArrayList;
import java.util.Arrays;
import java.util.OptionalInt;

/**

 */
public class toOffer11_2_73 {

    // 输入: piles = [30,11,23,4,20], H = 5 输出: 30
    public static void main(String[] args) {
        int[] piles = new int[]{3,6,7,11};
        int h = 8;
        System.out.println(minEatingSpeed(piles, h));

    }

    public static int minEatingSpeed(int[] piles, int h) {
        int right = Arrays.stream(piles).max().getAsInt();
        int left = 0;
        while (left <= right){
            int mid = (left + right) >> 1;
            if (fun(piles, h, mid)){
                if (!fun(piles, h, mid - 1)){
                    return mid;
                }
                right = mid - 1;
            }else {
                left = mid + 1;
            }
        }
        return 0;
    }

    public static boolean fun(int[] piles, int h, int speed){
        int timeCount = 0;
        for (int pile : piles) {
            if (pile <= speed) timeCount++;
            else timeCount = timeCount + pile / speed + 1;
        }
        return h >= timeCount;
    }
}
